package main

import (
    "log"
    "os"
    "fmt"
    "time"
)


type LogFile struct {
	fp string
	fd *os.File
	lastDay int
}
var lf LogFile

func (lf *LogFile) Write(p []byte) (int, error) {
	//path += fmt.Sprintf("%02d%02d%02d.log", time.Now().Hour(), time.Now().Minute(), time.Now().Second())   
	currentday := time.Now().Year()*10000 + int(time.Now().Month()*100) + time.Now().Day()
	if lf.lastDay != currentday || lf.fd == nil {
		lf.fd.Close()
		path := fmt.Sprintf("./logs/%08d", currentday) 
		//fmt.Println("path:", path)
		err := os.MkdirAll(path , 0644)
		if err != nil {
			fmt.Printf("%s", err)
			return -1, err
		} 
		lf.fp = path + "/nstar.log" 
		os.Chmod(lf.fp, 0644)
		lf.fd, err = os.OpenFile(lf.fp, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
		lf.lastDay = currentday
		if err != nil {
    		fmt.Println("open log file failed", err)
        	return -1, err
    	}
	}
    n, err := lf.fd.Write(p)
    if err != nil {
    	fmt.Println("write log file failed", err)
        return -1, err
    }
    return n, err
}


func init() {
    //log.SetFlags(log.Ldate | log.Lmicroseconds)
    log.SetOutput(&lf)
}

func main() {
	i := 0
	for {
		i++
		log.Println("message", i)
		time.Sleep(time.Second * 1)
	}
}






